package com.icinfo.cloud.provider.punish.ucase.punishexecute.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.ConvertUpMoneyUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppendixDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.dto.*;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.enums.CaseDelayInstallmentAuditReasonEnum;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.enums.CaseDelayInstallmentTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.enums.CaseInstallmentPayDayTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.enums.CaseInstallmentRemainderTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.mapper.CaseDelayInstallmentDetailMapper;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.mapper.CaseDelayInstallmentMapper;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.model.CaseDelayInstallmentPayFine;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.model.CaseDelayInstallmentPayFineDetail;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.service.ICaseDelayInstallmentService;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.vo.CaseDelayInstallmentDocVo;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.vo.CaseDelayInstallmentVo;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.vo.CaseInstallmentDetailVo;
import com.icinfo.cloud.provider.punish.ucase.punishexecute.vo.CaseInstallmentListVo;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 申请延期（分期）缴纳罚款service实现类
 * @Author mahan
 * @Date 2022/9/20
 * @Version 1.0
 */
@Service
@Slf4j
public class CaseDelayInstallmentServiceImpl extends MyBatisServiceSupport implements ICaseDelayInstallmentService {

    @Resource
    private CaseDelayInstallmentMapper caseDelayInstallmentMapper;
    @Resource
    private CaseDelayInstallmentDetailMapper caseDelayInstallmentDetailMapper;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CaseMainDetailSimpleInfoMapper caseMainDetailSimpleInfoMapper;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;


    /**
     * 保存分期（延期）信息
     *
     * @param caseDelayInstallmentDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseDelayInstallmentDocVo saveDelayInstallment(CaseDelayInstallmentDto caseDelayInstallmentDto) {
        //校验是否已经存在审批通过的文书
        this.checkDocExist(caseDelayInstallmentDto.getCaseId(), caseDelayInstallmentDto.getPartyId());
        //校验参数
        this.checkParam(caseDelayInstallmentDto);
        //根据caseId查询数据
        CaseDelayInstallmentPayFine caseDelayInstallmentPayFine = new CaseDelayInstallmentPayFine();
        caseDelayInstallmentPayFine.setCaseId(caseDelayInstallmentDto.getCaseId());
        caseDelayInstallmentPayFine.setPartyId(caseDelayInstallmentDto.getPartyId());
        CaseDelayInstallmentPayFine queryRe = caseDelayInstallmentMapper.selectOne(caseDelayInstallmentPayFine);
        //不是空的话，做更新操作
        if (queryRe != null) {
            return this.update(queryRe, caseDelayInstallmentDto);
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        caseDelayInstallmentPayFine.setId(BaseUtil.createUid());
        caseDelayInstallmentPayFine.setDelayInstallmentType(caseDelayInstallmentDto.getDelayInstallmentType());
        caseDelayInstallmentPayFine.setCreateTime(localDateTime);
        caseDelayInstallmentPayFine.setPartyId(caseDelayInstallmentDto.getPartyId());
        caseDelayInstallmentPayFine.setInstallmentPayTotalAmount(caseDelayInstallmentDto.getInstallmentPayTotalAmount());
        //创建人信息
        caseDelayInstallmentPayFine.setCreateUserId(String.valueOf(UserUtil.getUserInfo().getUserId()));
        caseDelayInstallmentPayFine.setCreateUserName(UserUtil.getUserInfo().getRealName());
        //延期
        if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_1.getCode().equals(caseDelayInstallmentDto.getDelayInstallmentType())) {
            caseDelayInstallmentPayFine.setDelayPayDate(caseDelayInstallmentDto.getDelayPayDate());
            caseDelayInstallmentMapper.insert(caseDelayInstallmentPayFine);
        }
        //分期
        else if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_2.getCode().equals(caseDelayInstallmentDto.getDelayInstallmentType())) {
            BeanUtil.copyProperties(caseDelayInstallmentDto.getCaseInstallmentDetail(), caseDelayInstallmentPayFine);
            caseDelayInstallmentMapper.insert(caseDelayInstallmentPayFine);
            //插入分期明细
            this.insertCaseInstallmentDetail(caseDelayInstallmentDto.getCaseInstallmentList(), caseDelayInstallmentPayFine.getId(), localDateTime);
        }
        //处理附件
        this.dealAppendixList(caseDelayInstallmentDto);

        //返回文书字段
        CaseDelayInstallmentDocDto dto = new CaseDelayInstallmentDocDto();
        dto.setCaseId(caseDelayInstallmentDto.getCaseId());
        dto.setPartyId(caseDelayInstallmentDto.getPartyId());
        return this.delayInstallmentDocInfo(dto);
    }

    /**
     * 修改分期（延期）信息
     *
     * @param caseDelayInstallmentDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaseDelayInstallmentDocVo updateDelayInstallment(CaseDelayInstallmentDto caseDelayInstallmentDto) {
        //校验是否已经存在审批通过的文书
        this.checkDocExist(caseDelayInstallmentDto.getCaseId(), caseDelayInstallmentDto.getPartyId());
        if (StrUtil.isEmpty(caseDelayInstallmentDto.getId())) {
            throw new BusinessException("主键ID不能为空");
        }
        //校验参数
        this.checkParam(caseDelayInstallmentDto);
        //根据ID查询数据
        CaseDelayInstallmentPayFine queryRe = caseDelayInstallmentMapper.selectByPrimaryKey(caseDelayInstallmentDto.getId());
        if (queryRe == null) {
            throw new BusinessException("延期（分期）记录不存在");
        }
        return this.update(queryRe, caseDelayInstallmentDto);
    }

    /**
     * 更新操作
     * @param queryRe
     * @param caseDelayInstallmentDto
     * @return
     */
    private CaseDelayInstallmentDocVo update(CaseDelayInstallmentPayFine queryRe, CaseDelayInstallmentDto caseDelayInstallmentDto){
        LocalDateTime localDateTime = LocalDateTime.now();
        //组装数据
        queryRe.setDelayInstallmentType(caseDelayInstallmentDto.getDelayInstallmentType());
        queryRe.setPartyId(caseDelayInstallmentDto.getPartyId());
        queryRe.setInstallmentPayTotalAmount(caseDelayInstallmentDto.getInstallmentPayTotalAmount());
        queryRe.setUpdateTime(localDateTime);
        //修改人信息
        queryRe.setUpdateUserId(String.valueOf(UserUtil.getUserInfo().getUserId()));
        queryRe.setUpdateUserName(UserUtil.getUserInfo().getRealName());
        //删除分期明细
        Example deleteExam = new Example(CaseDelayInstallmentPayFineDetail.class);
        deleteExam.createCriteria().andEqualTo("caseInstallmentId", queryRe.getId());
        caseDelayInstallmentDetailMapper.deleteByExample(deleteExam);
        if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_1.getCode().equals(caseDelayInstallmentDto.getDelayInstallmentType())) {
            queryRe.setDelayPayDate(caseDelayInstallmentDto.getDelayPayDate());
            caseDelayInstallmentMapper.updateByPrimaryKey(queryRe);
        }
        //分期
        else if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_2.getCode().equals(caseDelayInstallmentDto.getDelayInstallmentType())) {
            BeanUtil.copyProperties(caseDelayInstallmentDto.getCaseInstallmentDetail(), queryRe);
            caseDelayInstallmentMapper.updateByPrimaryKey(queryRe);
            //插入分期明细
            this.insertCaseInstallmentDetail(caseDelayInstallmentDto.getCaseInstallmentList(), queryRe.getId(), localDateTime);
        }
        //处理附件
        caseDelayInstallmentDto.setCaseId(queryRe.getCaseId());
        this.dealAppendixList(caseDelayInstallmentDto);

        //返回文书字段
        CaseDelayInstallmentDocDto dto = new CaseDelayInstallmentDocDto();
        dto.setCaseId(queryRe.getCaseId());
        dto.setPartyId(queryRe.getPartyId());
        return this.delayInstallmentDocInfo(dto);
    }

    /**
     * 获取分期（延期）信息
     *
     * @param dto
     */
    @Override
    public CaseDelayInstallmentVo delayInstallmentInfo(CaseDelayInstallmentDetailDto dto) {
        CaseDelayInstallmentVo reVo = new CaseDelayInstallmentVo();
        CaseDelayInstallmentPayFine caseDelayInstallmentPayFine = new CaseDelayInstallmentPayFine();
        caseDelayInstallmentPayFine.setCaseId(dto.getCaseId());
        caseDelayInstallmentPayFine.setPartyId(dto.getPartyId());
        CaseDelayInstallmentPayFine queryRe = caseDelayInstallmentMapper.selectOne(caseDelayInstallmentPayFine);
        //如果没有则返回null
        if (queryRe == null) {
            return reVo;
        }
        reVo = this.getDelayInstallmentDetail(queryRe);
        //获取附件信息
        reVo.setAppendixList(this.getAppendixList(dto.getCaseId(), dto.getDocumentCatalogCode()));
        return reVo;
    }

    /**
     * 案件详情页面，获取分期（延期）信息
     *
     * @param caseId
     */
    @Override
    public List<CaseDelayInstallmentVo> delayInstallmentInfo(String caseId) {
        CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        CaseDelayInstallmentPayFine caseDelayInstallmentPayFine = new CaseDelayInstallmentPayFine();
        caseDelayInstallmentPayFine.setCaseId(caseId);
        List<CaseDelayInstallmentPayFine> queryList = caseDelayInstallmentMapper.select(caseDelayInstallmentPayFine);
        //如果没有分期（延期），则返回null
        if (queryList == null || queryList.isEmpty()) {
            return null;
        }
        List<CaseDelayInstallmentVo> reList = CollUtil.newArrayList();
        for (CaseDelayInstallmentPayFine payFine : queryList) {
            if(!HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfoVo.getHandleType())){
                payFine.setPartyId("");
            }
            //判断是否完成审批，分期延期通知书，审批通过后，才展示
            int reCount = caseDelayInstallmentMapper.selectDelayInstallmentDocAuditPassCount(caseId, payFine.getPartyId(), DocumentKindEnum.DOC_KIND_DK2TYFQYQJNFKTZS.getCode());
            if(reCount > 0){
                CaseDelayInstallmentVo reVo = this.getDelayInstallmentDetail(payFine);
                //获取决定书缴纳罚款截止日期--以处罚决定书送达日期+15天，为截止日期
                Date jdsSdDate = caseDelayInstallmentMapper.selectJdsSdDate(payFine.getCaseId(), DocumentKindEnum.DOC_KIND_CFJDS.getCode());
                reVo.setDocumentPaymentEndDate(DateUtil.format(DateUtil.offsetDay(jdsSdDate, 15), DatePattern.NORM_DATE_PATTERN));
                reVo.setPartyId(payFine.getPartyId());
                //获取当事人姓名
                String partyName="";
                if(Constant.STRING_3.equals(caseMainInfoVo.getCasePartiesReasonType())&&Constant.STRING_1.equals(caseMainInfoVo.getHandleType())) {
                    List<CasePartiesRecordVo>  casePartiesRecords=casePartiesRecordService.getCasePartiesInfoVoList(caseId);
                    /*for (CasePartiesRecordVo vo:casePartiesRecords) {
                        if(StringUtils.isBlank(partyName)){
                            partyName=vo.getPartyName();
                        }else{
                            partyName=partyName+"、"+vo.getPartyName();
                        }
                    }*/
                }else {
                    CasePartiesRecord queryParam = new CasePartiesRecord();
                    queryParam.setPartyId(payFine.getPartyId());
                    queryParam.setStatus(Constant.WHETHER_STRING_YES);
                    CasePartiesRecord casePartiesRecord = casePartiesRecordMapper.selectOne(queryParam);
                    partyName=casePartiesRecord.getPartyName();
                }
                reVo.setPartyName(partyName);
                reList.add(reVo);
            }
        }
        if (reList == null || reList.isEmpty()) {
            return null;
        }
        return reList;
    }

    /**
     * 延期（分期）文书字段查询
     *
     * @param dto
     */
    @Override
    public CaseDelayInstallmentDocVo delayInstallmentDocInfo(CaseDelayInstallmentDocDto dto) {
        CaseDelayInstallmentDocVo reVo = new CaseDelayInstallmentDocVo();
        //判断案件是单当事人，还是多当事人
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        if (caseMainInfo == null) {
            log.info("-------为查询到案件信息，案件ID:{}--------", dto.getCaseId());
            return reVo;
        }
        //如果是单当事人，查出当事人id
        if (PartiesReasonTypeEnum.SINGLE_PARTY.getCode().equals(caseMainInfo.getCasePartiesReasonType()) || PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode().equals(caseMainInfo.getCasePartiesReasonType())) {
            CasePartiesRecord queryParam = new CasePartiesRecord();
            queryParam.setCaseId(dto.getCaseId());
            queryParam.setStatus(Constant.WHETHER_STRING_YES);
            CasePartiesRecord casePartiesRecord = casePartiesRecordMapper.selectOne(queryParam);
            if (casePartiesRecord != null) {
                dto.setPartyId(casePartiesRecord.getPartyId());
            }
        } else {//多当事人的话，要传partyId参数
            //当事人ID未传，返回空
            if (StrUtil.isEmpty(dto.getPartyId())) {
                log.info("-------多当事人时，当事人ID未传，案件ID:{}--------", dto.getCaseId());
                return reVo;
            }
        }
        //查询分期（延期）信息
        CaseDelayInstallmentPayFine caseDelayInstallmentPayFine = new CaseDelayInstallmentPayFine();
        caseDelayInstallmentPayFine.setCaseId(dto.getCaseId());
        caseDelayInstallmentPayFine.setPartyId(dto.getPartyId());
        CaseDelayInstallmentPayFine queryRe = caseDelayInstallmentMapper.selectOne(caseDelayInstallmentPayFine);
        if (queryRe == null) {
            log.info("-------未查询到案件相关的分期（延期）信息，案件ID:{}--------", dto.getCaseId());
            return reVo;
        }
        //获取延期日期
        if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_1.getCode().equals(queryRe.getDelayInstallmentType())) {
            reVo.setDelayDate(DateUtil.formatChineseDate(DateUtil.parseDate(queryRe.getDelayPayDate().format(DateTimeFormatter.ISO_DATE)), true));
        } else if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_2.getCode().equals(queryRe.getDelayInstallmentType())) {
            //获取分期明细
            reVo.setInstallmentRecords(this.getInstallmentStr(queryRe.getId()));
        }
        //审批表审批事由
        reVo.setDelayInstallmentAuditReason(CaseDelayInstallmentAuditReasonEnum.getValueByCode(queryRe.getDelayInstallmentType()));
        //获取罚款金额
        if (StrUtil.isNotEmpty(queryRe.getInstallmentPayTotalAmount())) {
            reVo.setPunishMoney(ConvertUpMoneyUtil.toChinese(queryRe.getInstallmentPayTotalAmount()));
        }
        //获取延期分期类型
        reVo.setDelayInstallmentType(queryRe.getDelayInstallmentType());
        return reVo;
    }

    /**
     * 获取案件处罚金额
     *
     * @param dto
     * @return
     */
    @Override
    public String getCasePunishMoney(CaseDelayInstallmentPunishMoneyDto dto) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        if (caseMainInfo == null) {
            throw new BusinessException("未查询到案件信息");
        }
        //如果是多个当事人，partId必传
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType()) && StrUtil.isEmpty(dto.getPartyId())) {
            throw new BusinessException("当事人ID不能为空");
        }
        //如果是普通程序
        if (CaseTypeEnum.NORMAL_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
            //多当事人分别处罚，查case_main_detail_auxiliary_info表,涉及金额字段，拟处罚金额：draft_punish_money
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType()) &&
                    HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
                Example queryExam = new Example(CaseMainDetailAuxiliaryInfo.class);
                queryExam.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("partyId", dto.getPartyId());
                List<CaseMainDetailAuxiliaryInfo> list = caseMainDetailAuxiliaryInfoMapper.selectByExample(queryExam);
                if (list != null && !list.isEmpty()) {
                    CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = list.get(0);
                    return caseMainDetailAuxiliaryInfo.getDraftPunishMoney();
                }
            } else {//其他情况，查询case_main_detail_info表,涉及金额字段，拟处罚金额：draft_punish_money；
                CaseMainDetailInfo queryParam = new CaseMainDetailInfo();
                queryParam.setCaseId(caseMainInfo.getId());
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectOne(queryParam);
                return caseMainDetailInfo.getDraftPunishMoney();
            }
        } else if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {//简易程序
            CaseMainDetailSimpleInfo queryParam = new CaseMainDetailSimpleInfo();
            queryParam.setCaseId(caseMainInfo.getId());
            CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoMapper.selectOne(queryParam);
            return caseMainDetailSimpleInfo.getDraftPunishMoney();
        }
        return null;
    }

    /**
     * 获取文书中，分期明细字符串（所有期数串一起）
     *
     * @param caseInstallmentId
     * @return
     */
    private String getInstallmentStr(String caseInstallmentId) {
        Example queryExam = new Example(CaseDelayInstallmentPayFineDetail.class);
        queryExam.createCriteria().andEqualTo("caseInstallmentId", caseInstallmentId);
        queryExam.orderBy("installmentSort").asc();
        List<CaseDelayInstallmentPayFineDetail> list = caseDelayInstallmentDetailMapper.selectByExample(queryExam);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            CaseDelayInstallmentPayFineDetail detail = list.get(i);
            stringBuffer.append(detail.getInstallmentNumber());
            stringBuffer.append("至");
            stringBuffer.append(DateUtil.formatChineseDate(DateUtil.parseDate(detail.getInstallmentPayDate()), true));
            stringBuffer.append("前，缴纳罚款");
            stringBuffer.append(ConvertUpMoneyUtil.toChinese(detail.getInstallmentPayAmount()));
            if (i != list.size() - 1) {
                stringBuffer.append("；");
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 获取详情
     *
     * @param payFine
     * @return
     */
    private CaseDelayInstallmentVo getDelayInstallmentDetail(CaseDelayInstallmentPayFine payFine) {
        CaseDelayInstallmentVo reVo = new CaseDelayInstallmentVo();
        //公共参数
        reVo.setId(payFine.getId());
        reVo.setCaseId(payFine.getCaseId());
        reVo.setDelayInstallmentType(payFine.getDelayInstallmentType());
        reVo.setDelayInstallmentTypeText(CaseDelayInstallmentTypeEnum.getValueByCode(payFine.getDelayInstallmentType()));
        reVo.setDelayPayDate(payFine.getDelayPayDate());
        reVo.setInstallmentPayTotalAmount(payFine.getInstallmentPayTotalAmount());
        reVo.setCaseInstallmentDetail(new CaseInstallmentDetailVo());
        //分期参数
        if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_2.getCode().equals(payFine.getDelayInstallmentType())) {
            CaseInstallmentDetailVo caseInstallmentDetail = new CaseInstallmentDetailVo();
            BeanUtil.copyProperties(payFine, caseInstallmentDetail);
            caseInstallmentDetail.setInstallmentPayDayTypeText(CaseInstallmentPayDayTypeEnum.getValueByCode(payFine.getInstallmentPayDayType()));
            caseInstallmentDetail.setInstallmentRemainderTypeText(CaseInstallmentRemainderTypeEnum.getValueByCode(payFine.getInstallmentRemainderType()));
            reVo.setCaseInstallmentDetail(caseInstallmentDetail);
            //获取分期明细
            Example queryExam = new Example(CaseDelayInstallmentPayFineDetail.class);
            queryExam.createCriteria().andEqualTo("caseInstallmentId", payFine.getId());
            queryExam.orderBy("installmentSort").asc();
            List<CaseDelayInstallmentPayFineDetail> list = caseDelayInstallmentDetailMapper.selectByExample(queryExam);
            List<CaseInstallmentListVo> caseInstallmentList = CollUtil.newArrayList();
            list.forEach(u -> {
                CaseInstallmentListVo vo = new CaseInstallmentListVo();
                BeanUtil.copyProperties(u, vo);
                caseInstallmentList.add(vo);
            });
            reVo.setCaseInstallmentList(caseInstallmentList);
        }
        return reVo;
    }

    /**
     * 获取附件列表
     *
     * @param caseId
     * @param documentCatalogCode
     * @return
     */
    private List<AppendixDto> getAppendixList(String caseId, String documentCatalogCode) {
        Example appendixExample = new Example(CaseAppendixRecord.class);
        appendixExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isDelete", "0");
        List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
        List<AppendixDto> appendixList = new ArrayList<>();
        if (caseAppendixRecords != null && !caseAppendixRecords.isEmpty()) {
            for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
                AppendixDto appendixDto = new AppendixDto();
                BeanUtil.copyProperties(caseAppendixRecord, appendixDto);
                appendixList.add(appendixDto);
            }
        }
        return appendixList;
    }

    /**
     * 保存附件信息
     */
    private void dealAppendixList(CaseDelayInstallmentDto dto) {
        if (StrUtil.isEmpty(dto.getDocumentCatalogCode())) {
            throw new BusinessException("文书目录编码不能为空");
        }
        //删除之前的附件(逻辑删除)
        caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCode(dto.getCaseId(), dto.getDocumentCatalogCode());
        if (dto.getAppendixList() != null && !dto.getAppendixList().isEmpty()) {
            for (AppendixDto appendixDto : dto.getAppendixList()) {
                CaseAppendixRecord record = new CaseAppendixRecord();
                BeanUtil.copyProperties(appendixDto, record);
                record.setCaseStageName(CaseStageEnum.PUNISH_EXECUTION.getDes());
                record.setCaseStageCode(CaseStageEnum.PUNISH_EXECUTION.getCode());
                record.setCaseId(dto.getCaseId());
                record.setDocumentCatalogCode(dto.getDocumentCatalogCode());
                Boolean re = caseAppendixRecordService.saveCaseAppendixRecord(record);
                if (!re) {
                    throw new BusinessException("附件保存失败");
                }
            }
        }
    }

    /**
     * 批量保存分期明细
     *
     * @param caseInstallmentList
     * @param caseInstallmentId
     * @param localDateTime
     */
    private void insertCaseInstallmentDetail(List<CaseInstallmentListDto> caseInstallmentList, String caseInstallmentId, LocalDateTime localDateTime) {
        caseInstallmentList.forEach(u -> {
            CaseDelayInstallmentPayFineDetail detail = new CaseDelayInstallmentPayFineDetail();
            BeanUtil.copyProperties(u, detail);
            detail.setCaseInstallmentId(caseInstallmentId);
            detail.setId(BaseUtil.createUid());
            detail.setCreateTime(localDateTime);
            caseDelayInstallmentDetailMapper.insert(detail);
        });
    }

    /**
     * 查询案件是否已经有正在审核，以及审核通过的记录
     * 如果存在，则不能进行修改和新增
     * @param caseId
     * @param partyId
     */
    private void checkDocExist(String caseId, String partyId){
        //只有分别处罚时，才需要传partyId
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if(!HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())){
            partyId = "";
        }
        int reCount = caseDelayInstallmentMapper.selectDelayInstallmentDocAuditPassPendingCount(caseId, partyId, DocumentKindEnum.DOC_KIND_DK2TYFQYQJNFKTZS.getCode());
        if(reCount > 0){
            throw new BusinessException("当前当事人已存在审核通过的分期（延期）通知书，请勿重复操作");
        }
    }

    /**
     * 校验参数
     *
     * @param caseDelayInstallmentDto
     */
    private void checkParam(CaseDelayInstallmentDto caseDelayInstallmentDto) {
        if (UserUtil.getUserInfo() == null) {
            throw new BusinessException("获取当前用户信息失败");
        }
        //参数校验
        if (!CaseDelayInstallmentTypeEnum.isLegalEnumCode(caseDelayInstallmentDto.getDelayInstallmentType())) {
            throw new BusinessException("分期（延期）类型错误");
        }
        //如果是延期，则校验延期参数（新增或者修改延期数据都需校验）
        if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_1.getCode().equals(caseDelayInstallmentDto.getDelayInstallmentType())) {
            if (caseDelayInstallmentDto.getDelayPayDate() == null) {
                throw new BusinessException("延期罚款截止日期不能为空");
            }
            //延期时间不能早于当天
            if (LocalDate.now().until(caseDelayInstallmentDto.getDelayPayDate(), ChronoUnit.DAYS) < 1) {
                throw new BusinessException("延期罚款截止日期要晚于当前日期");
            }
        }
        //如果是分期，则校验分期参数（新增或者修改分期数据都需校验）
        else if (CaseDelayInstallmentTypeEnum.DELAY_INSTALLMENT_TYPE_2.getCode().equals(caseDelayInstallmentDto.getDelayInstallmentType())) {
            this.checkInstallmentDetailParam(caseDelayInstallmentDto.getCaseInstallmentDetail());
            if (caseDelayInstallmentDto.getCaseInstallmentList() == null || caseDelayInstallmentDto.getCaseInstallmentList().isEmpty()) {
                throw new BusinessException("分期明细列表不能为空");
            }
        }
        if (caseDelayInstallmentDto.getAppendixList() != null && !caseDelayInstallmentDto.getAppendixList().isEmpty()) {
            if (StrUtil.isEmpty(caseDelayInstallmentDto.getDocumentCatalogCode())) {
                throw new BusinessException("文书目录编码不能为空");
            }
        }
    }

    /**
     * 校验分期参数
     *
     * @param dto
     */
    private void checkInstallmentDetailParam(CaseInstallmentDetailDto dto) {
        if (dto == null) {
            throw new BusinessException("分期参数不能为空");
        }
        //校验是否为空
        CustomCheckParamUtil.doCheck(dto);
        //规则要求校验
        if (dto.getInstallmentNumber() < Constant.INTEGER_2 || dto.getInstallmentNumber() > Constant.INTEGER_24) {
            throw new BusinessException("分期期数在2（包含）至24（包含）之间");
        }
        long betweenMonth = DateUtil.betweenMonth(new Date(), DateUtil.parse(dto.getInstallmentStartPayMonth(), "yyyy-MM"), Boolean.TRUE);
        if (betweenMonth < 1) {
            throw new BusinessException("分期开始月份要大于当前月");
        }
        if (!CaseInstallmentRemainderTypeEnum.isLegalEnumCode(dto.getInstallmentRemainderType())) {
            throw new BusinessException("无法除尽金额归属类型错误");
        }
        if (!CaseInstallmentPayDayTypeEnum.isLegalEnumCode(dto.getInstallmentPayDayType())) {
            throw new BusinessException("每月缴纳日类型错误");
        }
        if (CaseInstallmentPayDayTypeEnum.INSTALLMENT_PAY_DAY_TYPE_3.getCode().equals(dto.getInstallmentPayDayType())) {
            if (dto.getInstallmentPayCustomDay() == null) {
                throw new BusinessException("自定义还款日期不能为空");
            }
            if (dto.getInstallmentPayCustomDay() > Constant.INTEGER_31) {
                throw new BusinessException("请选择正确的自定义还款日期");
            }
        }
    }


}
